﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using System.Collections.Generic;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using Newtonsoft.Json.Linq;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSpecialTemplateController : Controller
    {
        YqdContext ctx;

        public WxSpecialTemplateController(YqdContext ctx)
        {
            this.ctx = ctx;
        }

        [User]
        public ActionResult GetList()
        {
            var TaskID = Form.GetInt("TaskID");
            var TypeID = Form.GetInt("TypeID");
            var r = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID));
            return this.ToJson(new
            {
                success = true,
                totalcount = r.Count(),
                data = r.OrderBy(it => it.Tactic).ToList().Select(it => new
                {
                    it.TemplateID,
                    it.FieldID,
                    it.Name
                })
            });
        }

        [User]
        public ActionResult GetFieldList()
        {
            return this.ToJson(new
            {
                success = true,
                data = ctx.Yqd_SpecialTemplate.Where(it => !it.IsGeneral).OrderBy(it => it.Tactic).Select(it => new
                {
                    value = it.TemplateID,
                    text = it.Name
                })
            });
        }

        /// <summary>
        /// 添加专项任务模板
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_SpecialTemplate model)
        {
            model.Tactic = ctx.Database.MaxID("Yqd_SpecialTemplate", "Tactic");
            model.FieldID = "Field" + model.Tactic;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_SpecialTemplate.Add(model);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                model.TemplateID,
                ret
            });
        }
        
        [User]
        public ActionResult Delete()
        {
            var TemplateID = Form.GetInt("TemplateID");
            var ret = ctx.Database.ExecuteSql("delete from Yqd_SpecialTemplate where TemplateID={0};", TemplateID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult GetTamplateFile()
        {
            try
            {
                var TaskID = Form.GetInt("TaskID");
                var TypeID = Form.GetInt("TypeID");
                var temps = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID));
                const string filename = "督查任务模板表.xlsx";
                var path = Config.Yqdpath("/sys/xls/");
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                FileInfo file = new FileInfo(path + filename);
                if (file.Exists) file.Delete();
                var title = temps.OrderBy(it => it.Tactic).Select(it => it.Name).ToArray();
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("督查任务模板");
                    int index = 1;
                    foreach (string t in title)
                    {
                        worksheet.Cells[1, index].Style.Font.Name = "宋体";
                        worksheet.Cells[1, index].Style.Font.Bold = true;
                        worksheet.Cells[1, index].Style.Font.Size = 12;
                        worksheet.Cells.Style.ShrinkToFit = true;
                        worksheet.Row(1).Height = 30;
                        worksheet.Column(index).Width = 20;
                        worksheet.Row(1).CustomHeight = true;
                        worksheet.Cells[1, index].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells[1, index].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        worksheet.Cells[1, index].Value = t;
                        index++;
                    }
                    package.Save();
                    package.Dispose();
                    return Json(new
                    {
                        success = true,
                        filepath = "/sys/xls/" + filename
                    });
                }
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    ex.Message
                });
            }
        }

        [User]
        public ActionResult GetTargetList()
        {
            var TaskID = Form.GetInt("TaskID");
            var TypeID = Form.GetInt("TypeID");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var datas = ctx.Yqd_SpecialTarget.Where(it => it.TaskID == TaskID && it.TypeID == TypeID);
            var data = new List<object>();
            foreach (var d in datas)
            {
                if (d.Content.HasValue())
                {
                    data.Add(JObject.Parse(d.Content));
                }
            }
            var totalcount = data.Count();
            if (pagesize > 0)
            {
                data = data.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            return Json(new
            {
                success = true,
                totalcount,
                data
            });
        }

        public ActionResult Import()
        {
            var fn = Form.GetString("fn");
            var TaskID = Form.GetInt("TaskID");
            var TypeID = Form.GetInt("TypeID");
            var path = Config.Yqdpath();
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            FileInfo file = new FileInfo(path + fn);
            Fn.Log("路径：" + path + fn);
            if (file != null)
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets["督查任务模板"];
                    int rowCount = worksheet.Dimension.Rows;
                    int ColCount = worksheet.Dimension.Columns;
                    var headers = worksheet.Cells[1, 1, 1, ColCount].Select(it => it.Text).ToArray();
                    var fields = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID)).OrderBy(it => it.Tactic).Select(it => new { it.FieldID, it.Name }).ToList();
                    var record = new Dictionary<string, string>();
                    for (var row = 2; row <= rowCount; row++)
                    {
                        record.Clear();
                        var model = new Yqd_SpecialTarget();
                        model.TaskID = TaskID;
                        model.TypeID = TypeID;
                        for (var col = 1; col <= ColCount; col++)
                        {
                            var nt = worksheet.Cells[row, col].Value.ToString().Trim();
                            var f = fields.FirstOrDefault(it => it.Name.Trim() == headers[col-1].Trim());
                            if (f != null)  record.Add(f.FieldID, nt);
                        }
                        if (record.Count() > 0) model.Content = JObject.FromObject(record).ToString();
                        model.Instime = DateTime.Now;
                        model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                        model.UnitCode = WxUser.LogonInfo.UnitCode;
                        ctx.Yqd_SpecialTarget.Add(model);
                    }
                    var ret = ctx.SaveChanges();
                    return this.ToJson(new
                    {
                        success = true,
                        ret
                    });
                }
            }
            return this.ToJson(new
            {
                success = false
            });
        }

        [User]
        public ActionResult Clear()
        {
            var TaskID = Form.GetInt("TaskID");
            var TypeID = Form.GetInt("TypeID");
            var ret = ctx.Database.ExecuteSql("delete from Yqd_SpecialTarget where TaskID={0} and TypeID={1};", TaskID, TypeID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
